package com.ljm.sys.org.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ljm.common.constants.SecurityConstants;
import com.ljm.common.dto.UserInfoDto;
import com.ljm.common.enums.DataStatus;
import com.ljm.common.enums.ResultStatus;
import com.ljm.common.page.PageDto;
import com.ljm.common.util.AssertUtil;
import com.ljm.common.util.PageUtil;
import com.ljm.security.util.UserUtil;
import com.ljm.service.BaseServiceImpl;
import com.ljm.sys.auth.service.ISysAuthUserRoleService;
import com.ljm.sys.org.api.SysOrgUserApi;
import com.ljm.sys.org.dto.SysOrgUserDto;
import com.ljm.sys.org.entity.SysOrgUser;
import com.ljm.sys.org.mapper.SysOrgUserMapper;
import com.ljm.sys.org.service.ISysOrgUserDepartService;
import com.ljm.sys.org.service.ISysOrgUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author HuamingChen
 * @since 2018-12-19
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class SysOrgUserServiceImpl extends BaseServiceImpl<SysOrgUserMapper, SysOrgUser>
        implements ISysOrgUserService, SysOrgUserApi {

    /**
     * 角色接口
     */
    @Resource
    private ISysAuthUserRoleService sysAuthUserRoleService;
    /**
     * 用户数据接口
     */
    @Resource
    private SysOrgUserMapper sysOrgUserMapper;

    /**
     * 部门关联接口
     */
    @Resource
    private ISysOrgUserDepartService sysOrgUserDepartService;

    @Override
    public List<SysOrgUserDto> getAllUser(){
        List<SysOrgUserDto> list=new ArrayList<>();
        LambdaQueryWrapper<SysOrgUser> wrapper=new LambdaQueryWrapper<>();
        if(!UserUtil.getRole().contains(SecurityConstants.ROLE_ADMIN)){
            wrapper.eq(SysOrgUser::getId,UserUtil.getCurUser().getOrgId());
        }
        List<SysOrgUser> pos=this.list(wrapper);
        if(CollectionUtils.isNotEmpty(pos)){
            pos.forEach(po->{
                SysOrgUserDto dto=new SysOrgUserDto();
                po.setLoginPwd(null);
                mapperFacade.map(po,dto);
                list.add(dto);
            });
        }
        return list;
    }

    @Override
    public void saveData(SysOrgUserDto dto, UserInfoDto curUser) {
        SysOrgUser po=new SysOrgUser();
        mapperFacade.map(dto,po);
        if(null==dto.getId()){
            //校验用户是否存在
            if(this.checkIsExict(po.getLoginName())){
                AssertUtil.throwException(ResultStatus.FIAL.getCode(),"该用户已经存在");
            }
            po.setCreateTime(LocalDateTime.now());
            po.setCreater(curUser.getLoginName());
            po.setStatus(DataStatus.NORMAL.getCode());
            po.setOrgId(curUser.getOrgId());
            this.save(po);
        }else{
            po.setEditor(curUser.getLoginName());
            po.setEditTime(LocalDateTime.now());
            this.updateById(po);
        }
        //保存部门信息
        sysOrgUserDepartService.userRefDept(dto.getDeptIds(),po.getId(),curUser);
        // 保存角色信息
        sysAuthUserRoleService.userRefRole(new ArrayList<>(dto.getRoles()),po.getId(),curUser);
    }

    /**
     * 校验用户是否存在
     * @param loginName 账号
     * @return 是否存在结果
     */
    private boolean checkIsExict(String loginName){
        boolean result=false;
        QueryWrapper<SysOrgUser> wrapper= new QueryWrapper<>();
        wrapper.eq("login_name",loginName);
        if(this.count(wrapper)>0){
            result=true;
        }
        return result;
    }

    @Override
    public void delData(List<Long> ids) {
        if(CollectionUtils.isEmpty(ids)){
            AssertUtil.throwException(ResultStatus.FIAL.getCode(),"请选择要删除的列");
        }
        this.removeByIds(ids);
    }

    @Override
    public SysOrgUserDto getDataById(Long id) {
        if(null==id){
            AssertUtil.throwException(ResultStatus.FIAL.getCode(),"主键为空");
        }
        SysOrgUser po=this.getById(id);
        if(po!=null){
            SysOrgUserDto dto=new SysOrgUserDto();
            mapperFacade.map(po,dto);
            dto.setLoginPwd(null);
            //查询部门信息
            dto.setDeptIds(sysOrgUserDepartService.getRefDeptByUserId(dto.getId()));
            // 查询角色信息
            dto.setRoles(sysAuthUserRoleService.getDataByUserId(dto.getId()));
            return dto;
        }else{
            return null;
        }
    }

    @Override
    public PageDto<SysOrgUserDto> getDataByPage(String fullName,String loginName, String realName, String identityNo, String email, Integer pageNo, Integer pageSize) {
        PageDto<SysOrgUserDto> pageDto=new PageDto<>(pageNo,pageSize);
        Integer total=sysOrgUserMapper.countRow(fullName,loginName,realName,identityNo,email);
        if(total>0){
            List<SysOrgUser> pos=sysOrgUserMapper.getPageRecord(fullName,loginName,realName,identityNo,email, PageUtil.getStartRow(pageNo,pageSize),pageSize);
            if(CollectionUtils.isNotEmpty(pos)){
                pageDto.setRecords(mapperFacade.mapAsList(pos,SysOrgUserDto.class));
                pageDto.setTotal(total);
            }
        }
        return pageDto;
    }

    @Override
    public Map<Class, Class> classMap() {
        Map<Class, Class> map=new HashMap<>();
        map.put(SysOrgUser.class,SysOrgUserDto.class);
        return map;
    }
}
